package com.myworkspace.standard.web.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.myworkspace.standard.common.config.UploadConfig;
import com.myworkspace.standard.web.dao.IndexDao;
import com.myworkspace.standard.web.mapper.IndexMapper;
import com.myworkspace.standard.web.model.OsFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@Service
public class IndexService extends ServiceImpl<IndexMapper,OsFile> {
    @Resource
    private UploadConfig uploadConfig;
    @Resource
    private IndexDao indexDao;

    public void uploadFile(MultipartFile multipartFile) throws Exception {
        String filename = multipartFile.getOriginalFilename();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String format = df.format(LocalDateTime.now());
        String fileDirPath = uploadConfig.getUploadPath() + format;
        File fileDir = new File(fileDirPath);
        if (!fileDir.exists()) {
            boolean mkdir = fileDir.mkdir();
            System.out.println(mkdir);
            fileDir = null;

        }
        String afterFix = filename.substring(filename.lastIndexOf("."));
        String newFilename = UUID.randomUUID().toString().replaceAll("-", "") + afterFix;
        String path = uploadConfig.getUploadPath() + format + "/" + newFilename;
        OsFile osFile = new OsFile();
        osFile.setFileName(filename);
        osFile.setFilePath(path);
        osFile.setUploadTime(System.currentTimeMillis());
        osFile.setFileSize(String.valueOf(multipartFile.getSize()));
        osFile.setFileUrl("82.157.154/download/" + format + "/" + newFilename);
        Integer i = indexDao.saveOsFile(osFile);
        System.out.println(i);
        File file = new File(path);
        multipartFile.transferTo(file);
    }

    public List<Map<String, Object>> getFileList() {
        List<Map<String, Object>> list = indexDao.getFileList();
        return list;

    }

    @Transactional
    public void updateTest() throws Exception {
        OsFile osFile = new OsFile();
        osFile.setId(1L);
        save(osFile);
//        int i = 1 / 0;
        indexDao.update(1L);

    }
}
